package com.lysj.bhp.withdraw.job;


import com.lysj.bhp.investment.domain.Reward;
import com.lysj.bhp.util.json.JacksonUtil;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import com.lysj.bhp.withdraw.base.WithdrawContent;
import com.lysj.bhp.withdraw.domain.WithDraw;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.Optional;

@Component
public class WithdrawJob extends WithdrawContent {


    @Resource
    Web3j web3j;

    private static Logger logger = LoggerFactory.getLogger(WithdrawJob.class);

    /*第一次10秒后执行，当执行完后0.2秒再执行，保证一秒并发不超过5个*/
    @Scheduled(initialDelay = 5000, fixedDelay = 5000)
    public void queryWithdraw() {
        logger.info("WithdrawJob is Starting ...");

        WithDraw withDraw = withdrawRepository.findFirstByTransctionStatusOrderByLastQueryTimeAsc(1);
        if (withDraw == null) { // 空值
            logger.info("Have not task ...");
            return;
        }
        if (withDraw.getTxHash() == null || "".equals(withDraw.getTxHash())) { // 没有交易hash,系统错误
            logger.error("Find a error withdraw ...");
            withDraw.setTransctionStatus(-1);
            withdrawRepository.save(withDraw);
            return;
        }
        try {
            Optional<TransactionReceipt> transactionReceiptOptional = web3j.ethGetTransactionReceipt(withDraw.getTxHash()).send().getTransactionReceipt();
            if (!transactionReceiptOptional.isPresent()) { // 没有交易回复,更新时间并退出循环
                logger.info(withDraw.getTxHash() + ": Hava not receipt ...");
                withDraw.setLastQueryTime(System.currentTimeMillis());
                withdrawRepository.save(withDraw);
                return;
            }
            logger.info(withDraw.getTxHash() + ": Hava receipt ..."); // 收到交易回复
            TransactionReceipt transactionReceipt = transactionReceiptOptional.get();
            if ("0x1".equals(transactionReceipt.getStatus())) { // 交易成功
                logger.info(withDraw.getTxHash() + ": return a success receipt"); // 收到一个成功的交易回复
                withDraw.setTransctionStatus(2);
                withDraw.setTransctionReceipt(JacksonUtil.toJson(transactionReceipt));

                //  将订单标记为已经完成
                // 开始处理完成转币的流程
                if (withDraw.getStatus() != 0) {
                    logger.error("This withdraw already deal,not allowed redeal ...");
                    withdrawRepository.save(withDraw);
                    return;
                }
                withDraw.setStatus(1);
                withDraw.setCheckDate(new Date());
                withDraw.setCheckReason("转币成功(自动)");
                withDraw.setCheckStatus(1);

                //修改用户钱包中的余额总资产跟冻结余额
                switch (withDraw.getType()) {  //10:比特币;20:以太坊;100:BHPC;110:BHPC_Bouns
                    case 100:
                        BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(withDraw.getUserId());
                        bhpcWallet.setFreezeBalance(bhpcWallet.getFreezeBalance().subtract(withDraw.getAmount()));
                        bhpcWallet.setBalance(bhpcWallet.getBalance().subtract(withDraw.getAmount()));
                        bhpcWalletRepository.save(bhpcWallet);
                        break;
                    case 20:
                        EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(withDraw.getUserId());
                        ethereumWallet.setFreezeBalance(ethereumWallet.getFreezeBalance().subtract(withDraw.getAmount()));
                        ethereumWallet.setBalance(ethereumWallet.getBalance().subtract(withDraw.getAmount()));
                        ethereumWalletRepository.save(ethereumWallet);
                        break;
                    case 10:
                        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(withDraw.getUserId());
                        bitCoinWallet.setFreezeBalance(bitCoinWallet.getFreezeBalance().subtract(withDraw.getAmount()));
                        bitCoinWallet.setBalance(bitCoinWallet.getBalance().subtract(withDraw.getAmount()));
                        bitcoinWalletRepository.save(bitCoinWallet);
                        break;
                    case 110:
                        //Reward reward = rewardRepository.findByUserId(currentUser().getUserId());
                        Reward reward = rewardRepository.findByUserIdAndType(withDraw.getUserId(), 100);
                        reward.setFreezeBalance(reward.getFreezeBalance().subtract(withDraw.getAmount()));
                        reward.setBalance(reward.getBalance().subtract(withDraw.getAmount()));
                        rewardRepository.save(reward);
                        break;
                    default:
                        break;
                }
                // 完成订单处理完毕

                withdrawRepository.save(withDraw);
            }else {
                logger.info(withDraw.getTxHash() + ": return a error receipt"); // 收到一个失败的交易回复
                withDraw.setTransctionStatus(3);
                withDraw.setTransctionReceipt(JacksonUtil.toJson(transactionReceipt));
                withdrawRepository.save(withDraw);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
